package com.jsj.bs.controller;

import com.github.pagehelper.PageInfo;
import com.jsj.bs.pojo.Result;
import com.jsj.bs.pojo.TbEssay;
import com.jsj.bs.service.TbEssayService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * (TbEssay)表控制层
 *
 * @author makejava
 * @since 2020-01-14 14:43:23
 */
@Controller
@RequestMapping("/tbEssay")
public class TbEssayController {

    private static final Logger LOGGER= LogManager.getLogger(TbEssayController.class);

    //返回的结果集 自定义
    private static final Result resultMsg = new Result();

    /**
     * 服务对象
     */
    @Autowired
    private TbEssayService tbEssayService;

    /**
     * 前台页面 进入文章详情页面
     *
     * @param essayId 主键
     * @return 单条数据
     */
    @RequestMapping(value = "/selectOne",method = RequestMethod.GET)
    public String selectOne(Integer essayId,Model model) {

        LOGGER.info("===selectOne===="+essayId);
        TbEssay tbEssay = tbEssayService.queryById(essayId);
        LOGGER.info("=============tbEssay======"+tbEssay);
        model.addAttribute("tbEssay",tbEssay );
        return "project";
    }
    /**
     * 前台 查询多条数据
     * @param page 页码
     * @param pageSize 页大小
     * @param essayType 类型
     * @return PageInfo<TbEssay> 分页数据集合
     */
    @RequestMapping("/queryAllBytype")

    public String queryAllBytype(@RequestParam(value = "page",defaultValue = "1") int page,
                                 @RequestParam(value = "pageSize",defaultValue = "5")int pageSize,
                                 Integer essayType, Model model){
        LOGGER.info("========/tbEssay/queryAllBytype======="+page+","+pageSize+","+essayType);
        if (essayType == null || essayType == -1){
            PageInfo<TbEssay> tbEssayPageInfo = tbEssayService.queryAll(page, pageSize, new TbEssay());
            model.addAttribute("essayType", null);
            model.addAttribute("tbEssayPageInfo", tbEssayPageInfo);
        }else {
            TbEssay tbEssay = new TbEssay();
            tbEssay.setEssayType(essayType);
            PageInfo<TbEssay> tbEssayPageInfo = tbEssayService.queryAll(page, pageSize, tbEssay);
            LOGGER.info("====tbEssayPageInfo======"+tbEssayPageInfo);
            model.addAttribute("essayType", essayType);
            model.addAttribute("tbEssayPageInfo", tbEssayPageInfo);
        }
        return "projects";
    }
    /**
     * 前台 查询多条数据
     * @param page 页码
     * @param pageSize 页大小
     * @param essayType 类型
     * @return PageInfo<TbEssay> 分页数据集合
     */
    @RequestMapping("queryAllOrderByIdDesc")
    @ResponseBody
    public PageInfo<TbEssay> queryAllOrderByIdDesc(@RequestParam(value = "page",defaultValue = "1") int page,
                                                   @RequestParam(value = "pageSize",defaultValue = "5")int pageSize,
                                                   int essayType){
        LOGGER.info("========/tbEssay/queryAllOrderByIdDesc======="+page+","+pageSize+","+essayType);
        TbEssay tbEssay = new TbEssay();
        tbEssay.setEssayType(essayType);
        PageInfo<TbEssay> tbEssayPageInfo = tbEssayService.queryAllOrderByIdDesc(page, pageSize, tbEssay);
//        LOGGER.info("====tbEssayPageInfo======"+tbEssayPageInfo);
        return tbEssayPageInfo;
    }

    /**
     * 后台展示数据
     * @param page
     * @param pageSize
     * @param tbEssay
     * @param model
     * @return
     */
    @RequestMapping(value = "/searchEssays", method = RequestMethod.GET)
    public String searchEssays(@RequestParam(value = "page", defaultValue = "1") int page,
                                @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
                                TbEssay tbEssay, Integer essayType, Model model) {
        LOGGER.info("==========文章类型是===="+essayType);
        //按类型查找，如果为空就查询全部
        tbEssay.setEssayType(essayType);
        LOGGER.info("=========" + page + "====" + pageSize + "=========" + tbEssay);
        PageInfo<TbEssay> tbEssayPageInfo = tbEssayService.queryAll(page, pageSize, tbEssay);
        LOGGER.info("======后台展示数据==========" + tbEssayPageInfo);
        model.addAttribute("essayType", essayType);
        model.addAttribute("tbEssayPageInfo", tbEssayPageInfo);
        return "essay-manager";

    }

    /**
     * 后台  文章是否通过   更新状态
     *
     * @param tbEssay
     * @return
     */
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public Result updateStatus(TbEssay tbEssay) {

        LOGGER.info("=======/tbEssay/updateStatus======" + tbEssay.getEssayId());
        Boolean result = tbEssayService.updateOk(tbEssay);
        if (result) {
            resultMsg.setFlag(true);
            resultMsg.setMsg("操作成功");
        } else {
            resultMsg.setFlag(false);
            resultMsg.setMsg("操作失败");
        }
        return resultMsg;
    }

    /**
     * 后台删除操作
     * @param essayId
     * @param model
     * @return
     */
    @RequestMapping(value = "/deleteOk",method = RequestMethod.GET)
    public String deleteOk(Integer essayId, Model model){

        boolean result = tbEssayService.deleteById(essayId);

        if (result){
            model.addAttribute("StatusMsg", -1);
            return "updateresult";
        }else {
            model.addAttribute("StatusMsg", -2);
            return "updateresult";
        }
    }

    /**
     * 后台添加文章信息  包括图片上传
     * @param tbEssay
     * @param file1
     * @param file2
     * @param file3
     * @param request
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/addEssay",method = RequestMethod.POST)
    public String addEssay(TbEssay tbEssay, MultipartFile file1, MultipartFile file2, MultipartFile file3,
                           HttpServletRequest request, Model model) throws IOException {

        LOGGER.info("=======添加的文章信息===="+tbEssay);
        String filename1 = null;
        String filename2 = null;
        String filename3 = null;
        //设置图片上传路径
        String path = request.getSession().getServletContext().getRealPath("/upload");
        LOGGER.info("========path===========" + path.toString());
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        //获取源文件名
        filename1 = file1.getOriginalFilename();
        filename2 = file2.getOriginalFilename();
        filename3 = file3.getOriginalFilename();
        LOGGER.info(filename1 + "---11111-----" + filename2+"========1111==="+filename3);
        //完成文件上传
        if (!filename1.equals("")) {
            //把文件的的名称设置成唯一值：uuid
            filename1 = UUID.randomUUID().toString().replace("-", "") + "_" + filename1;
            //将图片保存
            file1.transferTo(new File("F:/upload/" + filename1));
            //添加路径到数据库
            tbEssay.setEssayImg(filename1);
        }
        if (!filename2.equals("")) {
            //把文件的的名称设置成唯一值：uuid
            filename2 = UUID.randomUUID().toString().replace("-", "") + "_" + filename2;
            //将图片保存
            file2.transferTo(new File("F:/upload/" + filename2));
            //添加路径到数据库
            tbEssay.setEssayImg2(filename2);
        }
        if (!filename3.equals("")) {
            //把文件的的名称设置成唯一值：uuid
            filename3 = UUID.randomUUID().toString().replace("-", "") + "_" + filename3;
            //将图片保存
            file3.transferTo(new File("F:/upload/" + filename3));
            //添加路径到数据库
            tbEssay.setEssayImg3(filename3);
        }
         LOGGER.info(filename1 + "+============addEssay=Controller===========+" + filename2+"======"+filename3);

        //添加时间
        Date date = new Date();
        tbEssay.setAddTime(date);
        TbEssay essay = tbEssayService.insert(tbEssay);
        LOGGER.info(essay + "+=======文章添加=====addEssay=Controller===========+");
        if (essay != null){
            LOGGER.info("=======成功====成功===成功===成功=成功==");
            model.addAttribute("StatusMsg", 1);
            return "htresult";
        }else {
            LOGGER.info("=======失败====失败===失败===失败=失败==");
            model.addAttribute("StatusMsg", 2);
            return "htresult";
        }
    }
}